package com.xms.utils;

import com.xms.core.data.Entity;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 实体工具类
 * </p>
 *
 * @author migo
 * @since 2021/11/4
 */
public class EntityUtil {
    /**
     * bean对象转为实体
     *
     * @param bean
     * @param <TEntity>
     * @return
     * @throws IllegalAccessException
     */
    public static <TEntity> Entity fromBean(TEntity bean) throws IllegalAccessException {
        Class<?> clazz = bean.getClass();
        Entity result = new Entity(clazz.getSimpleName().toLowerCase());
        List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
        for (Field field : fields) {
            boolean isStatic = Modifier.isStatic(field.getModifiers());
            if(isStatic)
                continue;
            field.setAccessible(true);
            //null value abandon
            if (field.get(bean) == null)
                continue;
            result.setValue(field.getName().toLowerCase(), field.get(bean));
        }
        return result;
    }

    /**
     * Entity对象转为bean
     *
     * @param entity
     * @param clazz
     * @param <TBean>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <TBean> TBean toBean(Entity entity, Class<TBean> clazz) throws InstantiationException, IllegalAccessException {
        TBean bean = clazz.newInstance();
        List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
        for (Field field : fields) {
            field.setAccessible(true);
            String key = field.getName().toLowerCase();
            if (!entity.containsKey(key)) {
                continue;
            }
            Object value = entity.getValue(key);
            RefletUtil.setFieldValue(entity, field, value);
        }
        return bean;
    }
}
